<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="publish">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in ArtCateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select
              v-model="publish.state"
              placeholder="请选择状态"
              size="small"
            >
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click=";(q.pagenum = 1), getArtList()"
              size="small"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="resetList"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          @click="dialogVisible = true"
          size="small"
          class="btn-pub"
          >发表文章</el-button
        >
        <el-dialog
          title="提示"
          fullscreen
          @closed="$refs.publish.resetFields(), (coverImg = '')"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-form
            ref="publish"
            :rules="publishRules"
            :model="publish"
            label-width="80px"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="publish.title"></el-input>
            </el-form-item>
            <el-form-item label="文章类别" prop="cate_id">
              <el-select
                v-model="publish.cate_id"
                placeholder="请选择文章类别"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in ArtCateList"
                  :key="index"
                  :label="item.cate_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <!-- 使用 v-model 进行双向的数据绑定 -->
              <quill-editor v-model="publish.content"></quill-editor>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">
              <!-- 用来显示封面的图片 -->
              <img
                v-if="!coverImg"
                src="../../../assets/images/cover.jpg"
                class="cover-img"
                ref="imgRef"
              />
              <img v-else :src="coverImg" class="cover-img" ref="imgRef" />
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input
                @change="chooseImage"
                type="file"
                style="display: none"
                accept="image/*"
                ref="iptFile"
              />
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="$refs.iptFile.click()"
                >+ 选择封面</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="success"
                icon="el-icon-check"
                @click=";(publish.state = '已发布'), publishArticle()"
                round
                >发布</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click=";(publish.state = '草稿'), publishArticle()"
                round
                >存为草稿</el-button
              >
            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 查看文章详情的对话框 -->
        <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
          <h1 class="title">{{ artDetail.title }}</h1>

          <div class="info">
            <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
            <span>发布时间：{{ formDate(artDetail.pub_date) }}</span>
            <span>所属分类：{{ artDetail.cate_name }}</span>
            <span>状态：{{ artDetail.state }}</span>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <img
            :src="'http://www.liulongbin.top:3008' + artDetail.cover_img"
            alt=""
          />

          <div v-html="artDetail.content"></div>
        </el-dialog>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" stripe style="width: 100%">
        <el-table-column label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">{{
              row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类" width="180">
        </el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="scope">
            {{ formDate(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="danger"
              @click="remove(row.id)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false,
      // 文章的详情信息对象
      artDetail: {},
      artList: [],
      total: 0,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      publish: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      coverImg: '',
      publishRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章类别', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ],
        cover_img: [{ required: true, message: '请选择封面', trigger: 'blur' }]
      },
      dialogVisible: false
    }
  },
  methods: {
    formDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    async handleClose (done) {
      const result = await this.$confirm(
        '确认关闭？文章尚未保存',
        '提醒'
      ).catch((e) => e)
      //   console.log(result)
      if (result === 'confirm') done()
    },
    chooseImage (e) {
      // console.log(URL.createObjectURL(e.target.files[0]))
      if (e.target.files.length === 0) return this.$message.error('请选择图片')
      this.publish.cover_img = e.target.files[0]
      this.coverImg = URL.createObjectURL(e.target.files[0])
    },
    publishArticle () {
      this.$refs.publish.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写文章信息')
        // console.log(this.publish)
        const fd = new FormData()
        Object.keys(this.publish).forEach((key) => {
          fd.append(key, this.publish[key])
        })
        // console.log(fd)
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        if (this.publish.state === '已发布') {
          return this.$message.success(res.message)
        }
        this.$message.success('已存为草稿')
      })
    },
    async getArtList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.artList = res.data
      this.total = res.total
    },
    handleSizeChange (pagesize) {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.q.pagesize = pagesize
      this.getArtList()
    },
    handleCurrentChange (current) {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.q.pagenum = current
      this.getArtList()
    },
    resetList () {
      // 1. 重置查询参数对象
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      // 2. 重新发起请求
      this.getArtList()
    },
    async showDetail (id) {
      // 请求详情数据
      const { data: res } = await this.$http.get('/my/article/info', {
        params: { id }
      })
      if (res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
      // 展示对话框
      this.detailVisible = true
    },
    // 根据 id 删除文章
    async remove (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult === 'cancel') return

      const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })

      if (res.code !== 0) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')

      // 如果在刷新数据之前,当前页的数据只有 1 条，
      // 而且，当前的页码值 > 1，
      // 则说明当前页已没有数据可显示，需要让页码值 -1
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }

      this.getArtList()
    }
  },
  computed: {
    ...mapState('artCate', ['ArtCateList'])
  },
  created () {
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
  // 设置富文本编辑器的默认最小高度
  /deep/ .ql-editor {
    min-height: 300px;
  }
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
